package com.alibaba.shop.provider.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.shop.common.dto.ShopDetailDto;
import com.alibaba.shop.common.dto.ShopDto;
import com.alibaba.shop.common.util.BeanUtil;
import com.alibaba.shop.common.vo.R;
import com.alibaba.shop.provider.dao.ShopDao;
import com.alibaba.shop.provider.domain.Shop;
import com.alibaba.shop.provider.service.intf.ShopService;
import com.alibaba.shop.provider.third.TransportUtil;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.unit.DistanceUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopDao dao;

    @Override
    public R save(ShopDto dto) {
        if(dto!=null){
            /**
             *  原来用以下方式写，代码太臃肿
             *             Shop shop=new Shop();
             *             shop.setAddress(dto.getAddress());
             *             shop.setDelMoney(dto.getDelMoney());
             *             shop.setLat(dto.getLat());
             *             shop.setLon(dto.getLon());
             *             shop.setLogoOid(dto.getLogoOid());
             *             shop.setStartMoney(dto.getStartMoney());
             */

            Shop shop= BeanUtil.copy(Shop.class,dto.getClass().getDeclaredFields(),dto);
            shop.setFlag(1);
            shop.setCtime(new Date());
            if(dao.save(shop)!=null){
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R del(long id) {
        if(id>0){
            dao.deleteById(id);
            return R.ok();
        }
        return R.fail();
    }

    @Override
    public R searchList(double lon,double lat) {
        //如何实现es中geo搜索并排序
        //1.基于es实现geo搜索，并根据距离排序 升序
        List<String> list=TransportUtil.queryGeo("clouddata",lat,lon);
        //2.实例化集合，记录搜索的结果
        List<ShopDetailDto> dtos=new ArrayList<>(list.size());
        //3.遍历循环
        list.stream().forEach(s->{
            //4.解析json
            ShopDetailDto detailDto= JSON.parseObject(s,ShopDetailDto.class);
            //5.计算距离
            detailDto.setDistance( (int) GeoDistance.ARC.calculate(lat,lon, detailDto.getLocation().get("lat"), detailDto.getLocation().get("lon"), DistanceUnit.METERS));
            dtos.add(detailDto);
        });
        return R.ok(dtos);
    }

    @Override
    public R searchCircle(double lon, double lat, int length) {
        return null;
    }

    @Override
    public R searchDay() {
        return null;
    }
}
